/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Model.FarmBean;
import DAO.FarmUserDAO;
import DAO.PropertyDAO;
import Model.CartBean;
import Model.PropertyBean;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.sql.SQLException;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

/**
 *
 * @author amkreuz
 */
@Named(value = "farmUserController")
@ManagedBean
@SessionScoped
public class FarmUserController implements Serializable {

    private boolean signedIn;
    private FarmBean bean;
    private CartBean cart;

    public FarmUserController() {
        bean = (FarmBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user");
        if (bean == null) {
            bean = new FarmBean();
        }
        bean.setSignedIn(false);

        cart = (CartBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("cart");
        if (cart == null) {
            cart = new CartBean();
        }
        cart.setCount(0);

        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("user", bean);
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("cart", cart);
    }

    public boolean isSignedIn() {
        bean = (FarmBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user");
        return bean.isSignedIn();
    }

    public void setSignedIn(boolean signedIn) {
        this.signedIn = signedIn;
    }

    public boolean getSignedIn() {
        return this.signedIn;
    }
    
    public FarmBean getBean() {
        return bean;
    }

    public void setBean(FarmBean bean) {
        this.bean = bean;
    }

    public void upload(FileUploadEvent event) {
        FacesMessage msg = new FacesMessage("Success! ", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        // Do what you want with the file        
        try {
            copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void copyFile(String fileName, InputStream in) {
        try {
            // write the inputStream to a FileOutputStream
            OutputStream out = new FileOutputStream(new File("resources/images" + fileName));

            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }

            in.close();
            out.flush();
            out.close();

            System.out.println("New file created!");
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    public String createUser() throws SQLException {
        FarmUserDAO aUserDAO = new FarmUserDAO();    // Creating a new object each time.
        int rowCount = aUserDAO.createUser(bean); // Doing anything with the object after this?
        if (rowCount == 1) {
            System.out.println("User Added to Database");
            signInUser();
            return "HighLight.xhtml";
        } else {
            System.out.println("An Error Occurred");
            return "";
        }
    }

    public String signInUser() throws SQLException {
        FarmUserDAO aUserDAO = new FarmUserDAO();    // Creating a new object each time.
        int exCode = aUserDAO.signInUser(bean); // Doing anything with the object after this?
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("user", bean);
        if (exCode == -2) {
            System.out.println("Severe Error: Class Not Found");
            return "";
        } else if (exCode == -1) {
            System.out.println("Severe Error: Database Not Found");
            return "";
        } else if (exCode == 1) {
            System.out.println("Invalid Credentials");
            return "";
        } else if (exCode == 2) {
            System.out.println("Login Successful");
            bean.setSignedIn(true);
            return "index";
        } else {
            return "";
        }
    }

    public void signOutUser() {
        bean = new FarmBean();
        bean.setSignedIn(false);
    }

    public String getMessage() {
        bean = (FarmBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user");
        if (bean != null && bean.isSignedIn()) {
            return "Signed in as \"" + bean.getEmail() + ".\"";
        } else {
            return "Guest User";
        }
    }

    public String isAvailable(String user) {
        FarmUserDAO aUserDAO = new FarmUserDAO();
        String result = "    Please choose a valid username.";

        if (!user.isEmpty()) {
            try {
                aUserDAO.init();
                if (aUserDAO.isAvailable(user)) {
                    result = "    Username is available.";
                } else {
                    result = "    Username is unavailable.";
                }
                aUserDAO.terminate();
            } catch (SQLException e) {
                e.printStackTrace();
                result = "    Error while accessing database.";
            }
        }
        return result;
    }

    public void schedAppointment(String apptmt) {
        if (bean.isSignedIn()) {
            String to = bean.getEmail();
            String from = "bllim@ilstu.edu";
            String host = "smtp.ilstu.edu";

            // Get system properties
            Properties properties = System.getProperties();
            properties.setProperty("mail.smtp.host", host);
            properties.setProperty("mail.user", "");
            properties.setProperty("mail.password", "");
            Session session = Session.getDefaultInstance(properties);

            try {
                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(from));
                message.addRecipient(Message.RecipientType.TO,
                        new InternetAddress(to));
                message.setSubject("Farm_App: Appointment Request");
                message.setContent("<h3>You have requested an appointment at what you described as the following date and time:</h3><br/>" + apptmt, "text/html");
                Transport.send(message);
                System.out.println("Sent client message successfully....");
            } catch (MessagingException mex) {
                mex.printStackTrace();
            }
            FarmBean fb = (FarmBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user");
            to = fb.getCurrentProperty().getEmail();
            try {
                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(from));
                message.addRecipient(Message.RecipientType.TO,
                        new InternetAddress(to));
                message.setSubject("Farm_App: Appointment Request");
                message.setContent("<h3>A client has requested an appointment at what they described as the following date and time:</h3><br/>" + apptmt, "text/html");
                Transport.send(message);
                System.out.println("Sent owner message successfully....");
            } catch (MessagingException mex) {
                mex.printStackTrace();
            }
            FacesMessage facesMessage = new FacesMessage("Appointment message sent!");
            FacesContext.getCurrentInstance().addMessage("abc", facesMessage);
        } else {
            FacesMessage facesMessage = new FacesMessage("You must be signed in to schedule an appointment.");
            FacesContext.getCurrentInstance().addMessage("abc", facesMessage);
        }
    }

    public int getCartCount() {
        return cart.getCount();
    }

    public void addToCart() {
        FarmBean fb = (FarmBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user");
        PropertyBean pb = fb.getCurrentProperty();
        cart.addProperty(pb);
    }

    public void requestMoreInfo() {
        FarmBean fb = (FarmBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user");
        
        String to = fb.getCurrentProperty().getEmail();
        String from = fb.getEmail();
        String host = "smtp.ilstu.edu";

        // Get system properties
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.user", "");
        properties.setProperty("mail.password", "");
        Session session = Session.getDefaultInstance(properties);

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(to));
            message.setSubject("Farm_App: Request More Info: " + fb.getCurrentProperty().getAddress());
            message.setContent(fb.getEmail()+" has requested for more information on " +fb.getCurrentProperty().getAddress()+", "+fb.getCurrentProperty().getCity()+" "+fb.getCurrentProperty().getZip(), "text/html");
            Transport.send(message);
            System.out.println("Sent client message successfully....");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }

    
    public CartBean getCart() {
        return this.cart;
    }
    
    public void buyTheFarm() {
        int cartCount = this.getCartCount();
        ArrayList<PropertyBean> pb = this.getCart().getProperties();
        ArrayList<String> propNames = new ArrayList();
        for (int i = 0; i < cartCount; i++)
        {
            pb.get(i).setIsPurchased(true);
            propNames.add(pb.get(i).getAddress() + "' AND Zip=" + pb.get(i).getZip());
        }
        
        try {
            PropertyDAO propDAO = new PropertyDAO();
            propDAO.init();
            propDAO.purchaseLand(propNames);
            propDAO.terminate();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }
}